package com.abraham.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.abraham.activity.permission.PermissionsManager;
import com.abraham.activity.permission.PermissionsResultAction;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

public class SplashActivity extends AppCompatActivity {

    private Button mBtnGetPermission;
    private Button mBtnGoHomePage;
    private TextView mTvPermission;

    private String FRIST_REQUESER_PERMISSION="REQUESER_PERMISSION";
    private Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        this.mContext=SplashActivity.this;
        initView();


//        requestPermission();
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean isPermission=isCheckPermission(mContext,permissions);
        boolean  isRefusePermission=isCheckRefusePermission(mContext, permissions);
        Log.i("PermissionLog",  "isPermission is " +isPermission + "  isRefusePermission :" + isRefusePermission );
        boolean isRequestFirst=PreferencesUtils.getBoolean(mContext, FRIST_REQUESER_PERMISSION,true);

        if(isRequestFirst)
        {
            requestPermission();
        }

        else if(isRefusePermission)
        {
            showPermissionFailDialog();
        }
        else if (!isPermission)
        {
            showPermissionDialog();
        }
        else {
            Log.i("PermissionLog",  "isPermission is " +isPermission);
        }

    }

    public boolean isCheckPermission(Context context , String[] permissions)
    {
        PackageManager packageManager=context.getPackageManager();
        boolean isPermission=false;
        for (int i = 0; i < permissions.length; i++) {

            isPermission = (PackageManager.PERMISSION_GRANTED == packageManager.checkPermission(permissions[i], context.getPackageName()));

            if(!isPermission)
            {
                return  false;
            }
        }
        return isPermission;


        //ActivityCompat.shouldShowRequestPermissionRationale(SplashActivity.this, permission)
    }

    /**
     * 是否有拒绝的权限
     * @param context
     * @param permissions
     * @return
     */
    public boolean isCheckRefusePermission(Context context ,String[] permissions)
    {
        PackageManager packageManager=context.getPackageManager();
        boolean isPermission=false;
        for (int i = 0; i < permissions.length; i++) {

             isPermission = ActivityCompat.shouldShowRequestPermissionRationale(SplashActivity.this, permissions[i]);

            if(isPermission)
            {
                Log.i("PermissionLog",  " 拒绝的权限  :" +permissions[i]);
                return  true;
            }
        }
        return isPermission;
    }


    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE , Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WAKE_LOCK};


    private void requestPermission() {
        Log.i("PermissionLog", "requestPermission");
        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this,permissions
                , new PermissionsResultAction() {
                    @Override
                    public void onGranted() {
                        PreferencesUtils.getBoolean(mContext, FRIST_REQUESER_PERMISSION,false);
                        Log.i("PermissionLog", "权限通过。。");
                    }

                    @Override
                    public void onDenied(String permission) {
                        PreferencesUtils.getBoolean(mContext, FRIST_REQUESER_PERMISSION,false);
                        Log.i("PermissionLog", "权限不通过。。" + permission);
                    }
                }
        );
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);

        for (int i = 0; i < grantResults.length ; i++) {

            if(grantResults[i]==-1)
            {
                if(!ActivityCompat.shouldShowRequestPermissionRationale(SplashActivity.this, permissions[i]))
                {
                    showPermissionFailDialog();
                    return;
                }
                else {
                    showPermissionDialog();
                    return;
                }

            }
            Log.i("PermissionLog", "同意 grantResults 。。" + grantResults[i]);

        }

    }

    private void initView() {
        mBtnGetPermission = (Button) findViewById(R.id.btn_get_permission);
        mBtnGoHomePage = (Button) findViewById(R.id.btn_go_home_page);
        mTvPermission = (TextView) findViewById(R.id.tv_permission);

        mBtnGetPermission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        mBtnGoHomePage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(SplashActivity.this,MainActivity.class));
            }
        });
    }

    /**
     * 权限提示
     */
    public void showPermissionDialog()
    {
        String title=mContext.getResources().getString(R.string.permission_title);
        String intdescription=mContext.getResources().getString(R.string.permission_content);
        new MaterialDialog.Builder(mContext)
                .title(title)
                .content(intdescription)
                .positiveText(mContext.getResources().getString(R.string.txt_continue))
                .negativeText(mContext.getResources().getString(R.string.cancel))
                .positiveColor(mContext.getResources().getColor(R.color.colorPrimary))
                .negativeColor(mContext.getResources().getColor(R.color.colorPrimary))
                .widgetColor(mContext.getResources().getColor(R.color.colorPrimary))//不再提醒的checkbox 颜色
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which)
                    {
                        switch (which)
                        {
                            case NEGATIVE:
                            case POSITIVE:
                                requestPermission();
                                break;
                        }
                    }
                }).show();
    }



    /**
     * 权限提示
     */
    public void showPermissionFailDialog()
    {
        String title=mContext.getResources().getString(R.string.permission_fail_title);
        String intdescription=mContext.getResources().getString(R.string.permission_fail_content);
        new MaterialDialog.Builder(mContext)
                .title(title)
                .content(intdescription)
                .positiveText(mContext.getResources().getString(R.string.btn_go_settings))
                .positiveColor(mContext.getResources().getColor(R.color.colorPrimary))
                .widgetColor(mContext.getResources().getColor(R.color.colorPrimary))//不再提醒的checkbox 颜色
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which)
                    {
                        switch (which)
                        {
                            case NEGATIVE:
                            case POSITIVE:
                                Intent intent = new Intent();
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                if(Build.VERSION.SDK_INT >= 9){
                                    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                    intent.setData(Uri.fromParts("package", getPackageName(), null));
                                } else if(Build.VERSION.SDK_INT <= 8){
                                    intent.setAction(Intent.ACTION_VIEW);
                                    intent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
                                    intent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
                                }
                                startActivity(intent);
                                break;
                        }
                    }
                }).show();
    }
}
